package com.cunshe.service;

import com.cunshe.common.FileUtil;
import com.cunshe.dao.CorporateStyleDao;
import com.cunshe.domain.CorporateStyle;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CorporateStyleService {

    @Autowired
    private CorporateStyleDao corporateStyleDao;

    @Transactional(rollbackFor = Exception.class)
    public int insert(CorporateStyle record) {
        return corporateStyleDao.insert(record);
    }

    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        CorporateStyle corporateStyle = get(id);
        if(corporateStyle == null){
            return 0;
        }

        corporateStyleDao.delete(id);

        FileUtil.deleteFile(corporateStyle.getImageUrl());

        return 1;
    }

    @Transactional(rollbackFor = Exception.class)
    public int update(CorporateStyle record) {
        CorporateStyle corporateStyle = get(record.getId());
        if(corporateStyle == null){
            return 0;
        }

        if(!corporateStyle.getImageUrl().equals(record.getImageUrl())){
            FileUtil.deleteFile(corporateStyle.getImageUrl());
        }
        corporateStyleDao.update(record);

        return 1;
    }

    public CorporateStyle get(Long id) {
        if (id == null){
            return null;
        }
        return corporateStyleDao.list(CorporateStyle.builder().id(id).build())
                .stream()
                .findFirst()
                .orElse(null);
    }

    public List<CorporateStyle> getByType(Integer type) {
        return list(CorporateStyle.builder().type(type).build());
    }

    public List<CorporateStyle> list(CorporateStyle record) {
        PageHelper.orderBy(" sort_num DESC ");
        return corporateStyleDao.list(record);
    }

}